// pages/category/index.js
import { request } from '../../request/index.js';
// import { regeneratorRuntime } from '../../lib/runtime/runtime.js';
const regeneratorRuntime = require('../../lib/runtime/runtime.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    leftMenuList: [], // 左侧菜单list
    rightContent: [], // 右侧内容
    cacheList: [], // 缓存接口数据
    currentIndex: 0, // 当前被点击的菜单
    scrollTop: 0, // 右侧goods scroll-top位置
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  onShow: function () {
    let that = this;
    /* 缓存category数据 */
    /*
     1.先判断本地是否有数据
     2.没有旧的发送请求
     */
    const cates = wx.getStorageSync('cates');
    console.log('cates', cates);
    if (!cates.value) {
      that.getCates();
    } else {
      /* 判断catess是否过期 */
      if (Date.now() - cates.time > 5 * 60 * 1000) {
        that.getCates();
      } else {
        that.data.cacheList = cates.value;
        // 构造leftMenuList
        let leftMenuList = that.data.cacheList.map(item => {
          return item.cat_name;
        });
        // 构造rightContent
        let rightContent = that.data.cacheList[0].children;
        this.setData({
          leftMenuList: leftMenuList,
          rightContent: rightContent,
          cacheList: that.data.cacheList,
        });
      }
    }
  },
  // 获取分类数据
  async getCates() {
    let { cacheList } = this.data;
    const res = await request({ url: '/categories' });
    console.log(res);
    // 缓存接口数据
    cacheList = res;
    /* 缓存数据到本地 */
    wx.setStorageSync('cates', { time: Date.now(), value: this.cacheList });
    console.log(cacheList);
    // 构造leftMenuList
    let leftMenuList = cacheList.map(item => {
      return item.cat_name;
    });
    // 构造rightContent
    let rightContent = cacheList[0].children;
    console.log(leftMenuList);
    this.setData({
      leftMenuList,
      rightContent,
      cacheList
    });
    // console.log(this.data.leftMenuList);
    // console.log(this.data.rightContent);
    this.data.scrollTop = 0;
  },
  handleMenuTap: function (e) {
    console.log(e);
    let { cacheList } = this.data;
    if (cacheList.length === 0) {
      this.getCates();
    };
    /* 
    1.获取点击的index 
    2.赋值给curentIndex
    3.根据不同的索引渲染右侧的goods_content
    */
    const { index } = e.currentTarget.dataset;
    this.setData({
      currentIndex: index,
    });
    console.log(index);
    console.log(cacheList);
    let rightContent = cacheList[index].children;
    this.setData({
      rightContent,
    })
  }
})